<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="节点名称" prop="nodeName">
        <el-input v-model="queryParams.nodeName" placeholder="请输入节点名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="节点状态" prop="statusOpt">
        <el-select v-model="queryParams.statusOpt" placeholder="请选择节点状态" clearable size="small">
          <el-option v-for="dict in statusOptOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['labdata:flowDefination:edit']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleSaveSort" v-hasPermi="['labdata:flowDefination:edit']">保存排序</el-button>
      </el-col>
      <el-col :span="1.5" style="line-height: 30px;">请使用鼠标拖动节点行数据进行排序（如果次序不是自然数增长，务必需要拖动排序然后保存）</el-col>
    </el-row>

    <el-table v-loading="loading" :data="flowNodeList" ref="dragTable" highlight-current-row @selection-change="handleSelectionChange" row-key="nodeId">
      <el-table-column label="编号" prop="nodeNo" width="55" align="center" />
      <el-table-column label="流程名称" >
        <template slot-scope="scope">
          {{workflowName}}
        </template>
      </el-table-column>
      <el-table-column label="节点名称" align="center" prop="nodeName" width="100"/>
      <el-table-column label="节点类型" align="center" prop="nodeTypeOpt" :formatter="nodeTypeOptFormat" width="60"/>
      <el-table-column label="签批类型" align="center" prop="approvalTypeOpt" :formatter="approvalTypeOptFormat" width="60"/>
      <el-table-column label="签批角色" align="center" prop="approvalRoles" :formatter="getRoleName" width="160"/>
      <el-table-column label="节点状态" align="center" prop="statusOpt" :formatter="statusOptFormat" />
      <el-table-column label="节点次序" align="center" prop="nodeNo" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isPermit('labdata:flowDefination:edit')">
        <template slot-scope="scope" v-if="scope.row.nodeName!='Start' && scope.row.nodeName!='End'">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            >修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改流程节点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="460px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属流程" >
          <el-input v-model="workflowName"  class="input_w" disabled/>
        </el-form-item>
        <el-form-item label="节点名称" prop="nodeName">
          <el-input v-model="form.nodeName" placeholder="请输入节点名称" class="input_w"/>
        </el-form-item>
        <el-form-item label="节点类型" prop="nodeTypeOpt">
          <el-select v-model="form.nodeTypeOpt" placeholder="请选择节点类型" class="input_w">
            <el-option v-for="dict in nodeTypeOptOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签批类型" prop="approvalTypeOpt" >
          <el-select v-model="form.approvalTypeOpt" placeholder="请选择签批类型" class="input_w">
            <el-option v-for="dict in approvalTypeOptOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签批角色" prop="roleIds" >
          <el-select v-model="form.roleIds" multiple placeholder="请选择" class="input_w" >
            <el-option
              v-for="item in rolesOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="节点状态" prop="statusOpt">
          <el-select v-model="form.statusOpt" placeholder="请选择节点状态" class="input_w" >
            <el-option v-for="dict in statusOptOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可执行操作">
          <el-checkbox v-model="form.passed"  disabled >通过</el-checkbox>
          <el-checkbox v-model="form.refused" >拒绝</el-checkbox>
          <el-checkbox v-model="form.rectify">整改</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listFlowNode,
    listNodes,
    saveSort,
    getFlowNode,
    delFlowNode,
    addFlowNode,
    updateFlowNode,
    exportFlowNode
  } from "@/api/labdata/flowNode";
  import {
    getFlowDefination,
  } from "@/api/labdata/flowDefination";
  import {listRole} from "@/api/system/role";
  import Sortable from 'sortablejs';
  export default {
    name: "FlowNode",
    data() {
      return {
        workflowName:null,
        workflowId:null,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 流程节点表格数据
        flowNodeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 节点类型字典
        nodeTypeOptOptions: [],
        // 签批类型字典
        approvalTypeOptOptions: [],
        // 节点状态字典
        statusOptOptions: [],
        //角色分类
        rolesOptions:[],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 100,
          workflowId: null,
          nodeName: null,
          statusOpt: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          nodeName: [{
            required: true,
            message: "节点名称不能为空",
            trigger: "blur"
          }],
          nodeTypeOpt: [{
            required: true,
            message: "节点类型不能为空",
            trigger: "change"
          }],
          approvalTypeOpt: [{
            required: true,
            message: "签批类型不能为空",
            trigger: "change"
          }],
          /* roleIds: [{
            required: true,
            message: "签批角色不能为空",
            trigger: "blur"
          }], */
         /* statusOpt: [{
            required: true,
            message: "节点状态不能为空",
            trigger: "change"
          }], */
          /* nodeNo: [{
            required: true,
            message: "节点排序不能为空",
            trigger: "blur"
          }] */
        }
      };
    },
    mounted(){
      this.setSort();
    },
    created() {
      this.workflowId = this.$route.params && this.$route.params.workflowId;
      this.queryParams.workflowId  = this.workflowId;
      getFlowDefination(this.workflowId).then(response => {
        let result = response.data;
        this.workflowName = result.workflowName;
      });
      this.getList();
      this.getDicts("nodeTypeOpt").then(response => {
        this.nodeTypeOptOptions = response.data;
      });
      this.getDicts("approvalTypeOpt").then(response => {
        this.approvalTypeOptOptions = response.data;
      });
      this.getDicts("statusOpt").then(response => {
        this.statusOptOptions = response.data;
      });
      this.getRoles();
    },
    methods: {
      //setValue(){
        //this.$forceUpdate();
      //},
      handleSaveSort(){
        let datas = [];
        this.flowNodeList.forEach((item,index)=>{
          datas.push({
            nodeId:item.nodeId,
            nodeNo:1+index,
          });
        });
        saveSort(datas).then(response=>{
          this.$message.success('保存排序成功');
        });
      },
      /** 查询流程节点列表 */
      getList() {
        this.loading = true;
        listFlowNode(this.queryParams).then(response => {
          this.flowNodeList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      getRoles(){
        let roleForm = {};
        roleForm.pageNum = 1;
        roleForm.pageSize = 1000;
        listRole(roleForm).then(response =>{
          this.rolesOptions = response.rows;
        });
      },
      getRoleName(row, column){
        if(!row.approvalRoles){
          return '';
        }
        let roleIds = row.approvalRoles.split(',');
        let roleName = '';
        for(var k=0;k<roleIds.length;k++){
          for(var i=0; i< this.rolesOptions.length; i++){
            if(this.rolesOptions[i].roleId == roleIds[k]){
              if(roleName.length>0){
                roleName +=',';
              }
              roleName += this.rolesOptions[i].roleName;
              break;
            }
          }
        }
        return roleName;
      },
      // 节点类型字典翻译
      nodeTypeOptFormat(row, column) {
        return this.selectDictLabel(this.nodeTypeOptOptions, row.nodeTypeOpt);
      },
      // 签批类型字典翻译
      approvalTypeOptFormat(row, column) {
        return this.selectDictLabel(this.approvalTypeOptOptions, row.approvalTypeOpt);
      },
      // 节点状态字典翻译
      statusOptFormat(row, column) {
        return this.selectDictLabel(this.statusOptOptions, row.statusOpt);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.form = {};
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /**
       * 排序方法
       */
      setSort(){
        const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
        this.sortable = Sortable.create(el,{
          ghostClass:'sortable-ghost',
          setData:function(dataTransfer){
            dataTransfer.setData('Text', '')
          },
          onEnd: evt => {
            const targetRow = this.flowNodeList.splice(evt.oldIndex, 1)[0];
            this.flowNodeList.splice(evt.newIndex, 0, targetRow);
            this.flowNodeList.forEach((item,index)=>{
              item.nodeNo = 1+index;
            });

          }
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.nodeId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.form.passed=true;
        this.form.refused=true;
        this.form.rectify=false;
        this.form.statusOpt = '1';
        this.$forceUpdate();
        this.open = true;
        this.title = "添加流程节点";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const nodeId = row.nodeId || this.ids
        getFlowNode(nodeId).then(response => {
          this.form = response.data;
          this.form.passed=true;
          this.open = true;
          this.title = "修改流程节点";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.form.workflowId = this.workflowId;
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.nodeId != null) {
              updateFlowNode(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addFlowNode(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const nodeIds = row.nodeId || this.ids;
        this.$confirm('是否确认删除流程节点编号为"' + nodeIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFlowNode(nodeIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      isPermit(permitKey){
        if(this.$store.state.user.name=='admin'){
          return true;
        }
        let  permissions = this.$store.getters.permissions;
        return permissions.includes(permitKey);
      },
    }
  };
</script>
<style type="text/css" lang="scss" scoped>
  .input_w{
    width:260px;
  }
</style>
